<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\admin\model\Clue;
use app\admin\model\Company;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;

use FFMpeg\FFMpeg;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
	protected $noNeedRight = ['index', 'developer', 'company', 'clue'];
    /**
     * 查看
     */
    public function index()
    {
       /*  try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }
		
		$map = [];
		$groupIds = $this->auth->getGroupIds();
		if($groupIds[0] == 2)
		{
			$map['depart_id'] = $this->auth->depart_id;
		}
		$totalmember = Admin::where($map)->count();
			
        $this->view->assign([
			'totalmember'         => $totalmember,
            'totaluser'         => User::count(),
            'totaladdon'        => $totaladdon,
            'totaladmin'        => Admin::count(),
            'totalcategory'     => \app\common\model\Category::count(),
            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'       => count($dbTableList),
            'dbsize'            => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums'    => Attachment::count(),
            'attachmentsize'    => Attachment::sum('filesize'),
            'picturenums'       => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'       => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist)); */
		
		
		$todaycluenumber = Clue::whereTime('developtime', 'today')->count();
		$this->assign('todaycluenumber', $todaycluenumber);
		
		$week_starttime = strtotime('this week monday');
		$week_endtime = strtotime('this week sunday 23:59:59');
		$weekcluenumber = Clue::where('developtime', 'between time', [$week_starttime, $week_endtime])->count();
		$this->assign('weekcluenumber', $weekcluenumber);
		
		//获取本月开始的时间戳
		$month_starttime=mktime(0,0,0,date('m'),1,date('Y'));
		//获取本月结束的时间戳
		$month_endtime=mktime(23,59,59,date('m'),date('t'),date('Y'));
		$monthcluenumber = Clue::where('developtime', 'between time', [$month_starttime, $month_endtime])->count();
		$this->assign('monthcluenumber', $monthcluenumber);
		
		$year_starttime = mktime(0,0,0,1,1,date("Y"));
		$year_endtime = mktime(0,0,0,1,1,date("Y")+1)-1;
		$yearcluenumber = Clue::where('developtime', 'between time', [$year_starttime, $year_endtime])->count();
		$this->assign('yearcluenumber', $yearcluenumber);
		
		if(isset($_GET['year']))
		{
			$year = intval($_GET['year']);
		}
		else
		{
			$year = date('Y');
		}
		
		if(isset($_GET['month']))
		{
			$month = intval($_GET['month']);
		}
		else
		{
			$month = date('m');
		}
		
		if(isset($_GET['admin_id']))
		{
			$admin_id = intval($_GET['admin_id']);
		}
		else
		{
			$admin_id = '';
		}
		if(isset($_GET['nocluedays']))
		{
			$nocluedays = intval($_GET['nocluedays']);
		}
		else
		{
			$nocluedays = '';
		}
		
		$this->assign('year', $year);
		$this->assign('month', $month);
		$this->assign('admin_id', $admin_id);
		$this->assign('nocluedays', $nocluedays);
		$this->assignconfig('year', $year);
		$this->assignconfig('month', $month);
        return $this->view->fetch();
    }
	
	public function developer()
	{
		$this->request->filter(['strip_tags', 'trim']);
		
		list($where, $sort, $order, $offset, $limit) = $this->buildparams();
		
		$map = [];
		$year = intval($this->request->param('year'));
		$month = intval($this->request->param('month'));
		if($year)
		{
			if($month)
			{
				$starttime = strtotime($year.'-'.$month.'-01 00:00:00');
				$endtime = strtotime('+1 month', $starttime);
			}
			else
			{
				$starttime = strtotime($year.'-01-01 00:00:00');
				$endtime = strtotime(($year+1).'-01-01 00:00:00');
			}
		}
		else
		{
			$starttime = strtotime(date('Y').'-'.date('m').'-01 00:00:00');
			$endtime = strtotime('+1 month', $starttime);
		}
		$map['developtime'] = ['between time', [$starttime, $endtime]];

		$culeModel = new Clue();
		$list = $culeModel
			->with(['admin'])
			->field('admin_id, count(*) as xscount')
			->where($where)
			->where($map)
			->group('admin_id')
			->order($sort, $order)
			->paginate($limit);

		$result = array("total" => $list->total(), "rows" => $list->items());
		
		return json($result);
	}
	
	public function company()
	{
		$this->request->filter(['strip_tags', 'trim']);
		
		list($where, $sort, $order, $offset, $limit) = $this->buildparams();
		
		$map = [];
		$year = intval($this->request->param('year'));
		$month = intval($this->request->param('month'));
		if($year)
		{
			if($month)
			{
				$starttime = strtotime($year.'-'.$month.'-01 00:00:00');
				$endtime = strtotime('+1 month', $starttime);
			}
			else
			{
				$starttime = strtotime($year.'-01-01 00:00:00');
				$endtime = strtotime(($year+1).'-01-01 00:00:00');
			}
		}
		else
		{
			$starttime = strtotime(date('Y').'-'.date('m').'-01 00:00:00');
			$endtime = strtotime('+1 month', $starttime);
		}
		$map['developtime'] = ['between time', [$starttime, $endtime]];
		
		$culeModel = new Clue();
		$list = $culeModel
			->field('companyname, count(*) as xscount')
			->where($where)
			->where($map)
			->group('companyname')
			->order($sort, $order)
			->paginate($limit);

		$result = array("total" => $list->total(), "rows" => $list->items());
		
		return json($result);
	}
	
	public function clue()
	{
		$this->relationSearch = true;

		$this->request->filter(['strip_tags', 'trim']);
		
		$map = [];
		$admin_id = intval($this->request->param('admin_id'));
		$nocluedays = intval($this->request->param('nocluedays'));
		if($admin_id)
		{
			$map['admin_id'] = $admin_id;
		}
		
		$max_developtime = time()-86400*$nocluedays;
		$map['developtime'] = ['<=', $max_developtime];
		
		list($where, $sort, $order, $offset, $limit) = $this->buildparams();
		
		$culeModel = new Clue();
		$subQuery = $culeModel
			->field('company_id,max(developtime) as max_developtime')
			->where($where)
			->group('company_id')
			->buildSql();
					
		$list = $culeModel->field('companyname, admin_id, developtime')->alias('c')->join([$subQuery => 'sub'], 'c.company_id = sub.company_id and c.developtime = sub.max_developtime')->where($map)->group('c.company_id')->order($sort, $order)->paginate($limit);
		foreach($list as &$vo)
		{
			$adminname = Admin::where('id', $vo['admin_id'])->value('nickname');
			$vo['admin'] = $adminname;
		}

		$result = array("total" => $list->total(), "rows" => $list->items());
		
		return json($result);
	}
}
